<?php
/**
 * TotemToo Model All for TotemToo Component
 * 
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:components/
 * @license		GNU/GPL
 */

defined( '_JEXEC' ) or die('Restricted access');

jimport( 'joomla.application.component.model' );

/**
 * TotemToo Model
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class TotemTooModelTotemToo extends JModel
{
	/**
	 * TotemToo data array
	 *
	 * @var array
	 */
	var $_data;
	var $_id;
	/**
	 * TotemToo Totale Dati
	 *
	 * @var array
	 */
	var $_total = null;

	/**
	 * TotemToo Pagine
	 *
	 * @var array
	 */
	var $_pagination = null;

	/**
	 * Contruct of the class Model
	 * 
	 */
	function __construct()	{
		parent::__construct();

		global $mainframe, $option;

		$limit	= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $option.'limitstart', 'limitstart', 0, 'int' );

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
		
		$array = JRequest::getVar('cid',  array(0), '', 'array');
		$this->setId((int)$array[0]);
	}

	/**
	 * Returns the query
	 * @return string The query to be used to retrieve the rows from the database
	 */
	function _buildQuery($id = null)
	{
		$query = ' SELECT * '
			. ' FROM #__TotemToo_Immobili '
		;
		return $query;
	}

	/**
	* Method to store a record
	*
	* @access    public
	* @return    boolean    True on success
	*/
	function store()
	{

	$row =& $this->getTable('totemtoo');
	$data = JRequest::get( 'post');

	// Bind the form fields to the hello table
	if (!$row->bind($data)) {
		$this->setError($this->_db->getErrorMsg());
		JError::raiseWarning( 500, $row->getError());
		return false;
	}
	
	// Make sure the hello record is valid
	if (!$row->check()) {
		$this->setError($this->_db->getErrorMsg());
		return JError::raiseWarning( 500, $row->getError());
		return false;
	}
	
	// Store the web link table to the database
	if (!$row->store()) {
		$this->setError($this->_db->getErrorMsg());
		JError::raiseWarning( 500, $row->getError());
		return false;
	}
	
	return true;
	}

	/**
	* Method to set the setta l'identificativo unico
	*
	* @access    public
	* @param     int Hello identifier
	* @return    void
	*/
	function setId($id)
	{
		// Set id and wipe data
		$this->_id      = $id;
		$this->_data    = null;
	}

	/**
	 * Metodo per ottenere il totale dei record
	 * @return string The query to be used to retrieve the rows from the database
	 */
	function getTotal() {
		if (empty($this->_total)) {
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}
		return $this->_total;
	}
	
	/**
	 * Metodo per ottenere la paginazione del totale record
	 * @return string The query to be used to retrieve the rows from the database
	 */
	function getPagination() {
		if (empty($this->_pagination)) {
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}
		return $this->_pagination;
	}

	/**
	 * Retrieves the TotemToo data
	 * @return array Array of objects containing the data from the database
	 */
	function getData()
	{
		// Lets load the data if it doesn't already exist
		if (empty( $this->_data ))
		{ 
			$query = $this->_buildQuery($id);
			$pagination = $this->getPagination();
			$this->_data = $this->_getList($query, $pagination->limitstart, $pagination->limit);
		}
		return $this->_data; 
	}

	/**
	 * Edit a record or new record 
	 * @return boolean
	 */
	function getEdit() {
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT * FROM #__TotemToo_Immobili '.
				'  WHERE id = '.$this->_id;
			$this->_data = $this->_getList( $query ); 
		}
		if (!$this->_data) {
		//	$table = $this->getTable('totemtoo');
			$row[0] =& $this->getTable('totemtoo');
			// Verifico che ci sia la tabella vuota o non ci sia
			if ($row) {
				$this->_data = $row;
			} else { 
				$row[0]->id = 0;
				$this->_data = $row;
			}
		}
		return $this->_data;
	}

	function converti_jpg($numero) {
			$n_caratteri = strlen(strval($numero));
			$stringa = '';
			for($i=0; $i < 10 - $n_caratteri; $i++)    {
				$stringa = $stringa.'0';
    			}
			return $stringa.strval($numero);
	}

	/**
	 * Esistenza immagine immobile associata
	 * @return boolean
	 */
	function getImg_exist() {
		global $mainframe;
		$site =  $mainframe->getCfg('live_site');

		$str_jpg = $this->getImg();
		$percorso_jpg = JPATH_SITE . DS .'media/com_totemtoo/images/';
		$filename = $percorso_jpg.$str_jpg;
		$sroot =  $_SERVER["DOCUMENT_ROOT"];
		$imm_view = str_replace($sroot ,'/',$filename);
		if (file_exists($filename)) {
			return $imm_view;
		} else {
			return null;
		}
	}

	/**
	  * Ottieni nome immagine dall'id
	  * @return boolean
	  */
	function getImg() {
		return $this->converti_jpg($this->_id).'.jpg';
	}
	
	/**
	 * Cancella un record
	 * @return boolean
	 */
	function delete() {
		$cids = JRequest::getVar( 'cid', array(0), '', 'array' );
	// Carico la tabella associata a totem (cids è un array)
		$row =& $this->getTable('totemtoo');
		foreach($cids as $cid) {
			if (!$row->delete( $cid )) {
				$this->setError( $row->getErrorMsg() );
				return false;
			}
		}
		return true;
	}
	
function getComune($codice) {

		$query = "SELECT P.Prv_Sigla, C.Com_Provincia, C.Com_Codice, C.Com_Nome Descr FROM #__TotemToo_Comuni C, #__TotemToo_Provincie P, #__TotemToo_Regioni R WHERE (C.Com_Provincia = substring('$codice', 1, 3) AND  C.Com_Codice = substring('$codice', 4, 3));";
		
	    $database = &JFactory::GetDBO();
	    $database->setQuery($query);  
	    $oggetto = $database->loadAssocList();
		if ($oggetto) {
			foreach ($oggetto as $row) {
				$codice_com = $row['Descr'];
				return $codice_com;
			}
		}
		else { 
			return null; 
		}
}

function getCodici($tabella, $codice) {

		$query = "SELECT Codice, Descr FROM $tabella WHERE Codice = $codice;";
	    $database = &JFactory::GetDBO();
	    $database->setQuery($query);  
	    $oggetto = $database->loadAssocList();
		if ($oggetto) {
			foreach ($oggetto as $row) {
				$codice_prezzo = $row['Descr'];
				return $codice_prezzo;
			}
		}
		else { 
			return null; 
		}

}




	
	
}
